
class KankanwuInfo extends AbstractPlugin {

  static BASE_URL = 'https://www.kankanwu.com';

  async fetchWebsiteInfo() {
    const url = window.location.href;

    const parser = new DOMParser();
    const doc = parser.parseFromString(document.body.outerHTML, 'text/html');

    const playSources = [];

    let results = doc.querySelectorAll('.play-list-box');
    if(results.length === 0) {
      results = doc.querySelectorAll('.plau-ul-list');
    }
    results.forEach(result => {
      let links;
      const content = result.querySelector('.content');
      if(content) {
        links = content.querySelectorAll('.play-list a');
      } else {
        links = result.querySelectorAll('li a');
      }

      const episodes = [];
      links.forEach(link => {
        const episodeItem = new Episode();
        episodeItem.title = link.innerText;
        const href = link.getAttribute('href');
        if(href.startsWith('jianpian://')) return;
        episodeItem.link = href.startsWith('/') ? `${KankanwuInfo.BASE_URL}${href}` : href;
        episodes.push(episodeItem);
      });
      if(episodes.length > 0) {
        // episodes.reverse();
        playSources.push(new Source({
          title: '看看屋',
          episodes: episodes
        }));
      }
    });

    const websiteInfo = new WebsiteInfo();
    websiteInfo.type = 'video';
    const listItems = document.querySelectorAll('.bread-crumbs li');
    if(listItems.length > 0) {
      websiteInfo.title = listItems[listItems.length - 1].querySelector('a').textContent.trim();
    } else {
      const titleElement = doc.querySelector('.vod-n-l h1');
      if(titleElement) {
        websiteInfo.title = titleElement.textContent.trim();
      // } else {
      //  // <title>《百年孤独 第08集》高清在线观看 - 欧美剧电视剧 - 迅雷下载 - 看看屋手机版</title>
      }
    }
    websiteInfo.link = url;
    websiteInfo.sources = playSources;

    const playRegex = /\/player/;
    if(playRegex.test(url)) {
      websiteInfo.playUrl = await this.fetchPlayUrlInfo();
      let curEp = doc.querySelector('.play-list-box .play-list .current');
      if(!curEp) {
        curEp = doc.querySelector('.plau-ul-list li a.cur');
      }
      if(curEp) {
        const href = curEp.getAttribute('href');
        const curEpLink = href.startsWith('/') ? `${KankanwuInfo.BASE_URL}${href}` : href;
        [websiteInfo.sourceIndex, websiteInfo.episodeIndex] = AbstractPlugin.findEpisode(playSources, curEpLink);
      }
    }

    return websiteInfo;
  }

  async fetchPlayUrlInfo(url) {
    const urls = url ? await this.getPlayableUrlFromWebUrl(url)
                         : await this.getPlayableUrlFromWebBody(document.body.outerHTML);
    if(!urls) return null;

    const playUrl = new PlayUrlInfo();
    playUrl.type = 'video';
    playUrl.urls = urls;
    return playUrl;
  }

  async getPlayableUrlFromWebUrl(url) {
    const m3u8Match = url.match(/id=.*\.m3u8$/);
    if(m3u8Match) {
      const url = m3u8Match[0].substring(3);
      return [url];
    }

    const http_headers = {
      'User-Agent': KankanwuInfo.DEFAULT_USER_AGENT,
      'Origin': KankanwuInfo.BASE_URL,
      'Referer': url
    };
    const result = await doHttpRequestSync(url, { headers: http_headers });
    if(result.status !== 'success') {
      return null;
    }
    return this.getPlayableUrlFromWebBody(result.body);
  }

  async getPlayableUrlFromWebBody(body) {
    const iframeMatch = body.match(/<iframe[^>]+src="[^"]+/);
    if(iframeMatch) {
      const srcMatch = iframeMatch[0].match(/src="([^"]+)/);
      if(srcMatch) {
        let iframeUrl = srcMatch[1];
        if(iframeUrl.startsWith('http')) {
          return this.getPlayableUrlFromWebUrl(iframeUrl);
        }
      }
    }

    const videoSrcMatch = body.match(/<video src="(http[^"]+)"/);
    if(videoSrcMatch) {
      const url = videoSrcMatch[1];
      return [url];
    }

    const videoVarMatch = body.match(/var video\s*=\s*'([^']+)/);
    if(videoVarMatch) {
      const url = videoVarMatch[1];
      return [url];
    }

    const videoUrlMatch = body.match(/url:\s*'([^']+)'/);
    if(videoUrlMatch) {
      const url = videoUrlMatch[1];
      return [url];
    }

    return null;
  }

}
Registry.registerClass("KankanwuInfo", new KankanwuInfo())
